package cn.cc.baycar.service;

import cn.cc.baycar.mapper.mapper.SmallMiGoodsPayCarMapper;
import cn.cc.baycar.mapper.pojo.SmallMiGoodsPayCar;
import cn.cc.baycar.service.bo.AddPayCarDO;
import cn.cc.common.beanCopy.utils.BeanCopierUtil;
import cn.cc.common.contants.RedisKeyConstant;
import cn.cc.common.redis.RedisCommon;
import cn.cc.common.result.utils.RestResult;
import cn.cc.common.result.utils.RestResultEmum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;


/**
 * @description:redis监听
 * @auther: Mr.WuChao
 * @date: 2021/7/23 8:59
 * @return:
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private SmallMiGoodsPayCarMapper payCarMapper;

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        //TODO 登录设置有效期
        // redis监听时间与登录有效期一致
        // 当token失效时并且redis 过期 我去同步数据库
        // 获取到失效的 key，进行取消订单业务处理
        String expiredKey = message.toString();
        //通过：截取字符串
        String[] split = expiredKey.split(":");
        int i = split.length - 1;
        System.out.println(expiredKey);
        String str = split[i].toString();
        if (str.equals("Listener")) {
            System.out.println("吕一文傻逼");
            //删除数据库数据然后同步redis数据
            payCarMapper.removePayCar();
            //再次去拿redis 的数据
            Map<String, AddPayCarDO> hashAlls = redisCommon.getHashAll(RedisKeyConstant.SHOPPING_CAR_GOODS_CC_PAY_CAR, AddPayCarDO.class);
            Iterator<AddPayCarDO> iterator = hashAlls.values().iterator();
            while (iterator.hasNext()) {
                AddPayCarDO next = iterator.next();
                SmallMiGoodsPayCar payCar = BeanCopierUtil.copyObj(next, SmallMiGoodsPayCar.class);
                int insert = payCarMapper.insertSelective(payCar);
            }
        }
    }
}
